package servicios;

import java.util.Hashtable;

import javax.ejb.Stateless;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.InitialContext;

import entities.CasaCentral;

/**
 * Session Bean implementation class AdmJMSBean
 */
@Stateless
public class AdmJMSBean implements AdmJMS {

    /**
     * Default constructor. 
     */
    public AdmJMSBean() {
        // TODO Auto-generated constructor stub
    }

	@Override
	public boolean enviarPedidoMateriaPrima(String xml, CasaCentral casaCentral) {
		Hashtable<String,String> props = new Hashtable<String,String>();
        Boolean acept=false;
		props.put(InitialContext.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
//		if(casaCentral.getIp()!=null && !"".equalsIgnoreCase(casaCentral.getIp()))
//		        props.put(InitialContext.PROVIDER_URL, "jnp://"+casaCentral.getIp()+":1099");
//		else
//		        props.put(InitialContext.PROVIDER_URL, "jnp://localhost:1099");
		props.put(InitialContext.PROVIDER_URL, "jnp://localhost:1099");
		QueueConnection qCon = null;
		QueueSession qSession = null;
		QueueSender qSender = null;
		try {
	        InitialContext ctx = new InitialContext(props);
	
	        QueueConnectionFactory qfactory = (QueueConnectionFactory) ctx.lookup("ConnectionFactory");
	
	        Queue queue = (Queue) ctx.lookup("queue/pedidosMateriaPrimaQueue");
	
	        qCon = qfactory.createQueueConnection();
	        qSession = qCon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
	
	        qSender = qSession.createSender(queue);
	        
	        TextMessage message = qSession.createTextMessage();
	        message.setText(xml);
	
	        qSender.send(message);
	        acept=true;
			} catch (Exception e) {
			        System.out.println("Error al efectuar pedido: " + e);
			} finally {
				closeConnection(qCon, qSession, qSender);
			}
		return acept;
	}
	
	@Override
    public void enviarConfirmacionACasaCentral(String xml,CasaCentral casaCentral)  {
            Hashtable<String,String> props = new Hashtable<String,String>();
    props.put(InitialContext.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
    if(casaCentral.getIp()!=null && !"".equalsIgnoreCase(casaCentral.getIp()))
            props.put(InitialContext.PROVIDER_URL, "jnp://"+casaCentral.getIp()+":1099");
    else
            props.put(InitialContext.PROVIDER_URL, "jnp://localhost:1099");
    QueueConnection qCon = null;
    QueueSession qSession = null;
    QueueSender qSender = null;
    try {
            InitialContext ctx = new InitialContext(props);

            // buscar la Connection Factory en JNDI
            QueueConnectionFactory qfactory = (QueueConnectionFactory) ctx.lookup("ConnectionFactory");

            // buscar la Cola en JNDI
            Queue queue = (Queue) ctx.lookup("queue/ordenCompraAcepQueue");

            // crear la connection y la session a partir de la connection
            qCon = qfactory.createQueueConnection();
            qSession = qCon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);

            // crear un producer para enviar mensajes usando la session
            qSender = qSession.createSender(queue);
            
            // crear un mensaje de tipo text y setearle el contenido
            TextMessage message = qSession.createTextMessage();
            message.setText(xml);

            // enviar el mensaje
            qSender.send(message);
            
	    } catch (Exception e) {
	            System.out.println("Error al efectuar pedido: " + e);
	    } finally {
	    	closeConnection(qCon, qSession, qSender);
	    }
    }
	
	private void closeConnection(QueueConnection conn, QueueSession session,
	           QueueSender send) {
	   try { send.close(); } catch (Throwable e) {}
	   try { conn.stop();} catch (Throwable e) {}
	   try { session.close();} catch (Throwable e) {}
	}
    
    

}
